package com.example.designPattern.prototype.deepclone;

import java.io.*;

/**
 * 深拷贝原型类
 *
 * 格式化代码快捷键：Ctrl + Alt + L
 */
public class DeepPrototype implements Serializable, Cloneable {

    public String name;
    //对该引用类型的拷贝
    public DeepCloneableTarget deepCloneableTarget;


    //方式一、深拷贝  使用clone方法


    @Override
    protected Object clone() {
        Object deep = null;
        try {
            //完成对基本数据类型的属性的clone
            deep = super.clone();

            //完成对引用数据类型的属性的clone
            //得到该对象
            DeepPrototype deepPrototype = (DeepPrototype) deep;
            //得到对象的引用类型对象
            deepPrototype.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

            return deepPrototype;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //方式二、深拷贝   通过对象的序列化实现深拷贝
    public Object deepClone() {
//创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//将当前对象以输出流的方式输出

            //反序列化   将当前对象以输入流的方式读入
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype clone = (DeepPrototype) ois.readObject();

            return clone;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                ois.close();
                bis.close();
                oos.close();
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
